/*  header-comment
/*  file   : /Users/allan/Desktop/workSpace/react-hrm-h5/src/modules/hrCenter/statistics/index
/*  author : Allan
/*  date   : 2017-6-4 18:24:50
/*  last   : 2017-11-3 16:43:22
*/
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { WhiteSpace, Icon as DIcon, Badge } from "@ali/ding-ui";
import "./index.less";
import { setTitle, setRight, openLink } from "../../../utils/dingtalk.js";
import { setCacheData, getCacheData } from "../../../utils/storeCache.js";
import TitleBage from "../../../components/TitleBage";
import { set, get } from "../../../utils/db";
import { replaceSearch, getUrlSearchParam } from "../../../utils/urlParams";
import HelpModal from "../../../components/HelpModal";
import Icon from "../../../components/Icon/index.jsx";
import {
  fetchHrCenterInfo,
  fetchHrCenterTopInfo,
  fetchFragmentaryEmployeeCount
} from "../../../actions/hrCenter/";

const corpId = getUrlSearchParam("corpId");

//是否是预发环境
const isPre = window.location.href.indexOf("pre") !== -1 ? true : false;

const corpIds = ["dinge87f15a77973e1c1","ding10c505554116f7b735c2f4657eb6378f"];
const isWangding = corpIds.indexOf(corpId) !== -1;
//四个名单列表
const listColOrderAdmin = [
  // {
  //   title:"入职名单",
  //   img:"https://gw.alicdn.com/tps/TB19RptOpXXXXXQXFXXXXXXXXXX-102-102.png",
  //   url:"onJobList?list=departure"
  // },
  // {
  //   title: "离职名单",
  //   img: "https://gw.alicdn.com/tfs/TB1Q4qDiMMPMeJjy1XdXXasrXXa-102-102.png",
  //   url: "onJobList?list=departure"
  // }
  // {
  //   title:"转正名单",
  //   img:"https://gw.alicdn.com/tps/TB19xFfOpXXXXbBXVXXXXXXXXXX-102-102.png",
  //   url:"onJobList?list=departure"
  // },
  // {
  //   title:"调岗名单",
  //   img:"https://gw.alicdn.com/tfs/TB1Q4qDiMMPMeJjy1XdXXasrXXa-102-102.png",
  //   url:"onJobList?list=departure"
  // }
];
const zaizhiOrder = {
  title: "入职名单",
  img: "https://gw.alicdn.com/tfs/TB1gIaOdfDH8KJjy1XcXXcpdXXa-102-102.png"
}
const lizhiOrder = {
  title: "离职名单",
  img: "https://gw.alicdn.com/tfs/TB1sU9Pdb_I8KJjy1XaXXbsxpXa-102-102.png",
  url: "onJobList?list=departure"
}
const diaoOrder = {
  title: "调岗名单",
  img: "https://gw.alicdn.com/tfs/TB1LfOsdlfH8KJjy1XbXXbLdXXa-102-102.png"
}
const zhuanzhegnOrder = {
  title: "转正名单",
  img: "https://gw.alicdn.com/tfs/TB1jcaOdfDH8KJjy1XcXXcpdXXa-102-102.png"
}

if (isWangding) {
  // listColOrderAdmin.push(zaizhiOrder);
  // listColOrderAdmin.push(lizhiOrder);
  // listColOrderAdmin.push(diaoOrder);
  // listColOrderAdmin.push(zhuanzhegnOrder);
}else{
  listColOrderAdmin.push(lizhiOrder);
}

//数字链接
const innerLinkHash = {
  pendingEntry: "preJobList", //待入职
  totalOnJob: "onJobList", //在职员工
  totalProbationary: "onJobList?list=probation", //试用期
  pendingLeave: "pendingLeave" //待离职
};

//员工管理
const innerLinkHashPersonManage = [
  {
    key: "totalProbationary",
    hash: "onJobList?list=probation",
    title: "试用期"
  },
  {
    key: "totalOnJob",
    hash: "onJobList",
    title: "在职人员"
  },
  {
    key: "pendingLeave",
    hash: "pendingLeave",
    title: "待离职"
  }
];

//假勤管理
const leaveListAdmin = [
  {
    title: "假期管理",
    img: "https://gw.alicdn.com/tfs/TB1gZuea3nD8KJjy1XdXXaZsVXa-102-102.png",
    url: `https://${isPre
      ? "pre-"
      : ""}aflow.dingtalk.com/dingtalk/mobile/homepage.htm?corpid=${corpId}&dd_share=false&showmenu=true&swfrom=hrm#/leaveType`
  },
  {
    title: "考勤管理",
    img: "http://static.dingtalk.com/media/lALOcsYpu8zIzMg_200_200.png",
    url: `https://${isPre
      ? "pre-"
      : ""}attend.dingtalk.com/attend/index.html?corpId=${corpId}#stat`
  }
];

//导航行
const MenuLine = ({ title, children, onClick}) => {
  return (
    <div className="hr-m-w" onClick={() => {
      if(onClick){
        onClick();
      }
    }}>
      <span className="hr-w">
        <div className="hr-m-l">
          <span className='hr-m-main'>{title}</span>
        </div>
        <div className="hr-m-r">
          <span className="roster-title">
            {children}
          </span>
          <DIcon type="right" size="md" className="roster-arrow" />
        </div>
      </span>
    </div>
  )
}

const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    {
      dispatch,
      fetchHrCenterInfo,
      fetchHrCenterTopInfo,
      fetchFragmentaryEmployeeCount
    },
    dispatch
  )
});


@connect(mapStateToProps, mapDispatchToProps)
export default class Statistics extends Component {
  constructor(props) {
    super(props);
    const hideWaring = get(corpId + "_hideWaring");
    this.state = {
      hrCenterInfo: "",
      hrCenterTopInfo: "",
      fragmentaryEmployeeCount: "",
      aflowUrl: "", // 假期
      attendUrl: "", //考勤
      hideWaring: hideWaring
    };
    setTitle({
      title: "智能人事"
    });
  }

  componentDidMount() {
    this.getFragmentaryCount();
    this.getTopInfo();
    this.getInfo();
  }

  // 首页其他内容信息
  getInfo = async () => {
    const getHrCenterInfoV3 = "/hrmregister/mobile/workbench/getHrCenterInfoV3";
    const cacheData = await getCacheData(getHrCenterInfoV3);
    if (cacheData) {
      this.setState({
        hrCenterInfo: cacheData
      });
    }
    this.props.actions.fetchHrCenterInfo({ isCache: !!cacheData }).then(res => {
      if (res.success) {
        this.setState({
          hrCenterInfo: res.result
        });
        setCacheData(getHrCenterInfoV3, res.result);
      }
    });
  };
  // 待办事项列表、节日人数
  getTopInfo = async () => {
    const getScheduleIndexInfo =
      "/hrmregister/mobile/hrmSchedule/getScheduleIndexInfo";
    const cacheScheduleData = await getCacheData(getScheduleIndexInfo);
    if (cacheScheduleData) {
      this.setState({
        hrCenterTopInfo: cacheScheduleData
      });
    }
    this.props.actions
      .fetchHrCenterTopInfo({ isCache: !!cacheScheduleData })
      .then(res => {
        this.setState({
          hrCenterTopInfo: res.result
        });
        setCacheData(getScheduleIndexInfo, res.result);
      });
  };
  // 基本信息不完整员工数
  getFragmentaryCount = async () => {
    sessionStorage.removeItem("fragmentCount"); //
    const getFragmentaryEmployeeCount =
      "/hrmregister/mobile/emp/getFragmentaryEmployeeCount";
    const cacheFragmentaryEmployeeCount = await getCacheData(
      getFragmentaryEmployeeCount
    );
    if (cacheFragmentaryEmployeeCount) {
      this.setState({
        fragmentaryEmployeeCount: cacheFragmentaryEmployeeCount
      });
    }
    this.props.actions
      .fetchFragmentaryEmployeeCount({
        isCache: !!cacheFragmentaryEmployeeCount
      })
      .then(res => {
        // 在职列表需要使用有多少员工基本信息不完整
        sessionStorage.setItem("fragmentCount", res.result);
        this.setState({
          fragmentaryEmployeeCount: res.result
        });
        setCacheData(getFragmentaryEmployeeCount, res.result);
      });
  };

  componentWillUnmount() {
    window.needReload = null;
  }

  //待刷新
  needReload() {
    const t = this;
    window.needReload = function() {
      if (window.location.href.toLocaleLowerCase().indexOf("hrcenter") !== -1) {
        t.getInfo && t.getInfo();
      }
    };
  }

  toLink = url => {
    this.needReload();
    window.dd.biz.util.openLink({ url: url, enableShare: true });
  };

  link = (url, useOpenLink) => {
    if (useOpenLink) {
      this.toLink(url);
    } else {
      window.location.href = url;
    }
  };

  buildFlowItem(url, icon, name, useOpenLink) {
    return (
      <li
        className="menu-item"
        key={url}
        onClick={() => {
          window._rlog(`_manager_to_${name}`);
          this.link(url, useOpenLink);
        }}
      >
        <img src={icon} alt="" />
        <p>{name}</p>
      </li>
    );
  }

  buildNumberStatItem(url, number, text, useOpenLink) {
    return (
      <li
        className="menu-item"
        key={url}
        onClick={() => {
          if (number === 0) {
            const titleText = encodeURI(text);
            set("hrCenterPageLinkText", text);
            // this.toLink(`?text=${titleText}#/noDataPage`);
            const preUrl =
              window.location.protocol +
              "//" +
              window.location.host +
              window.location.pathname +
              `?text=${titleText}#/noDataPage`;
            this.link(preUrl, useOpenLink);
            return;
          }
          window._rlog(`_manager_to_${text}`);
          this.link(url, useOpenLink);
        }}
      >
        <div>
          <span>{number}</span>
        </div>
        <p>{text}</p>
      </li>
    );
  }

  buildItemGroup(itemGroup, title) {
    if (!itemGroup || itemGroup.length === 0) {
      return null;
    }
    const itemList = [];
    itemGroup.map((item, index) => {
      if (item.count < 0) {
        itemList.push(
          this.buildFlowItem(
            item.url,
            item.icon,
            item.name,
            item.useOpenLink,
            index % 2 === 0
          )
        );
      } else {
        itemList.push(
          this.buildNumberStatItem(
            item.url,
            item.count,
            item.name,
            item.useOpenLink,
            index % 2 === 0
          )
        );
      }
    });
    return (
      <div className="employee-roster">
        <h4>{title}</h4>
        <ul>{itemList}</ul>
      </div>
    );
  }

  buildStatisticModule(hrCenterInfo) {
    if (!hrCenterInfo || !hrCenterInfo.processItemGroup) {
      return null;
    }

    return (
      <div>
        {this.buildItemGroup(hrCenterInfo.processItemGroup.GROUP_HIRE, "入职管理")}
        <WhiteSpace size="lg" />

        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_DISMISSION,
          "离职管理"
        )}
        <WhiteSpace size="lg" />

        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_REGULAR,
          "转正管理"
        )}
        <WhiteSpace size="lg" />

        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_TRANSFER,
          "人事调动"
        )}
        <WhiteSpace size="lg" />

        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_ATTENDANCE,
          "假勤管理"
        )}
      </div>
    );
  }

  buildTopList(hrCenterTopInfo) {
    if (!hrCenterTopInfo) {
      return null;
    }

    return (
      <div
        className="list-wrap"
        onClick={() => {
          window._rlog(`_manager_to_todoList`);
          window.location.hash = "todoList";
        }}
      >
        {(hrCenterTopInfo.scheduleList.length != 0 ||
          (hrCenterTopInfo.birthdayNum > 0 ||
            hrCenterTopInfo.annualNum > 0)) && (
          <div className="list-body">
            {(hrCenterTopInfo.birthdayNum > 0 ||
              hrCenterTopInfo.annualNum > 0) && (
              <p className="festival">
                <i />
                {hrCenterTopInfo.birthdayNum > 0 &&
                  `本月有${hrCenterTopInfo.birthdayNum}人过生日`}
                {hrCenterTopInfo.birthdayNum > 0 &&
                  hrCenterTopInfo.annualNum > 0 &&
                  `，`}
                {hrCenterTopInfo.annualNum > 0 &&
                  `${hrCenterTopInfo.annualNum}人周年庆`}
              </p>
            )}
            {hrCenterTopInfo.scheduleList.length > 0 &&
              hrCenterTopInfo.scheduleList.map((item, index) => {
                // 调岗显示结构
                if (item.scheduleType === "调岗") {
                  if (item.laterDay) {
                    // 是否延期
                    return (
                      <p>
                        <i />
                        {item.laterDay && `${item.laterDay}天后`}
                        {item.userName}调岗到 {item.deptName}
                      </p>
                    );
                  }

                  return (
                    <p>
                      <i />
                      {item.delayDay !== "0" ? `超期${item.delayDay}天 ` : `今天`}
                      {item.userName}调岗到 {item.deptName}
                    </p>
                  );
                }
                // 非调岗显示结构
                if (item.laterDay) {
                  // 是否延期
                  return (
                    <p>
                      <i />
                      {item.laterDay && `${item.laterDay}天后`}
                      {item.userName} {item.deptName ? item.deptName : ""}{" "}
                      {item.scheduleType}
                    </p>
                  );
                }
                return (
                  <p>
                    <i />
                    {item.delayDay !== "0" ? `超期${item.delayDay}天 ` : `今天`}
                    {item.userName} {item.deptName ? item.deptName : ""}{" "}
                    {item.scheduleType}
                  </p>
                );
              })}
          </div>
        )}
      </div>
    );
  }

  //代办事项
  waitList() {
    const hrCenterTopInfo = this.state.hrCenterTopInfo;
    if (!hrCenterTopInfo) return "";
    const children = (<div >
      {hrCenterTopInfo.delayNum > 0 && (
        <div className="wait-list-title">
          共{hrCenterTopInfo.scheduleNum}条，超期{hrCenterTopInfo.delayNum}条
            </div>
      )}
      {hrCenterTopInfo.delayNum === "0" &&
        hrCenterTopInfo.scheduleNum > 0 && (
          <div className="wait-list-title">共{hrCenterTopInfo.scheduleNum}条</div>
        )}
      {hrCenterTopInfo.scheduleNum === "0" && <div className="wait-list-title">太棒了，无待办事项</div>}
    </div>)
    return (
      <MenuLine title="待办事项" hash="todoList" children={children} onClick={() => {
        window._rlog(`_manager_to_todoList`);
        window.location.hash = "todoList";
      }} />
    )
  }

  //人事审批管理
  adminContact(){
    const children = "入转调离同步花名册";
    return (
      <MenuLine title="人事审批管理" children={children} onClick={() => {
        window._rlog(`_manager_to_renshishenpi`);
        openLink("https://tms.dingtalk.com/markets/dingtalk/renshishenpi?wh_ttid=phone&dd_nav_bgcolor=FF3296FA")
      }} />)
  }

  //管理权限设置
  setHrRight(){
    const children = "设置人事子管理员";
    return (
      <MenuLine title="管理权限设置" children={children} onClick={()=>{
        window._rlog(`_manager_to_setHrRight`);
        window.location.href = `dingtalk://dingtalkclient/page/managerRoleSetting?corpId=${corpId}`;
      }}/>
    )
  }

  createDingMsg(fragmentaryEmployeeCount) {
    const url =
      window.location.origin +
      window.location.pathname +
      window.location.search +
      "#/steps";
    dd.biz.ding.create({
      users: fragmentaryEmployeeCount, // 用户列表，工号
      corpId: get("corpId"), // 企业id
      type: 2, // 附件类型 1：image  2：link
      alertType: 2, // 钉发送方式 0:电话, 1:短信, 2:应用内

      attachment: {
        title: "点击编辑基本信息",
        url: url,
        text: "进入钉钉智能人事维护个人基本信息",
        image: "https://gw.alicdn.com/tfs/TB13u27aOqAXuNjy1XdXXaYcVXa-88-88.png"
      }, // 附件信息
      text: "你的个人资料页缺少重要的基本信息，请马上维护更新", // 正文
      bizType: 0, // 业务类型 0：通知DING；1：任务；2：会议；
      onSuccess: function() {
        //onSuccess将在点击发送之后调用
      },
      onFail: function() {}
    });
  }

  buildTopCard() {
    const { fragmentaryEmployeeCount ,hideWaring} = this.state;
    const t = this;
    if (fragmentaryEmployeeCount.length > 0 && !isWangding && !hideWaring) {
      return (
        <div className="topCard">
          <div
            className="card-body"
            onClick={() => {
              window._rlog(`_manager_to_ding`);
              this.createDingMsg(fragmentaryEmployeeCount);
            }}
          >
            <img
              src="https://gw.alicdn.com/tfs/TB1hsaOdfDH8KJjy1XcXXcpdXXa-27-36.png"
              alt=""
            />
            <h5 style={{ fontWeight: "bold" }}>
              {fragmentaryEmployeeCount.length}名员工基本信息不完整
            </h5>
            <p>完善信息后，系统会提醒你最近有哪些员工要转正、周年或生日</p>
          </div>
          <span className="close" onClick={() => {
              set(corpId + "_hideWaring", true);
              t.setState({ hideWaring: true })
            }}>
            <Icon type="close"  />
          </span>
        </div>
      );
    }
  }
  goHashLink(hash, title = "", count = 1) {
    window._rlog("_manager_to_" + hash);
    if (count <= 0) {
      set("hrCenterPageLinkText", title);
      this.props.router.push("noDataPage");
      return;
    }
    // if(hash === "onJobList"){
    // 	this.props.router.push(hash);
    // 	return;
    // }
    this.props.router.push(hash);
  }

  render() {
    const {
      hrCenterInfo,
      hrCenterTopInfo,
      fragmentaryEmployeeCount,
      className
    } = this.state;
    //是否是主管理员
    const mainAdmin = window.__auth && window.__auth.admin;
    const t = this;
    return (
      <div className={`employee-manage-wrap ${className}` }>
        <HelpModal />

        <div className="waring-to-steps">
          {this.buildTopCard(fragmentaryEmployeeCount)}
        </div>
        
        {//代办提醒
          this.waitList()
        }
          {this.buildTopList(hrCenterTopInfo)}

        <WhiteSpace size="lg" />

        <div
          className="hr-m-w"
          onClick={() => {
            window._rlog(`_manager_to_${innerLinkHash.pendingEntry}`);
            t.goHashLink(innerLinkHash.pendingEntry, "待入职员工");
          }}
        >
          <span className="hr-w">
            <div className="hr-m-l">
              <span className="hr-m-main">办理入职</span>
            </div>
            <div className="hr-m-r">
              <span className="roster-title">
                <div>待入职</div>
                {hrCenterInfo.pendingEntry !== "0" ? (
                  <Badge text={hrCenterInfo.pendingEntry} />
                ) : (
                  ""
                )}
              </span>
              <DIcon type="right" size="md" className="roster-arrow" />
            </div>
          </span>
        </div>
        <WhiteSpace size="lg" />

        <div className="hr-m-e">
          <TitleBage title="花名册管理" />
          <ul className='hr-m-ul'>
            {
              innerLinkHashPersonManage.map((item) => <li className="hr-m-li" onClick={() => {
                  window._rlog(`_manager_to_${item.hash}`);
                  t.goHashLink(item.hash, item.title, hrCenterInfo[item.key]);
                }}
              >
                <div>
                  <span>{hrCenterInfo[item.key] || 0}</span>
                </div>
                <div className="hr-li-desc">{item.title}</div>
              </li>
            )}
          </ul>
          {/* <div className="hr-m-b" /> */}
          {
            !isWangding ? <div className="hr-m-col" style={{marginTop:40}}>
              {listColOrderAdmin.map(item => (
                <span
                  className="hr-m-li col-4"
                  onClick={() => {
                    if (!item.url) return;
                    window._rlog(`_manager_to_${item.url}`);
                    window.location.hash = item.url;
                  }}
                >
                  <img src={item.img} />
                  <div className="hr-li-desc">{item.title}</div>
                </span>
              ))}
            </div> : <div style={{ height: '40' }}></div>
          }
         
        </div>
        <WhiteSpace size="lg" />
        <div className="hr-m-e">
          <TitleBage title="假勤管理" />
          <div className="hr-m-col">
            {leaveListAdmin.map(item => (
              <span
                className="hr-m-li col-4"
                onClick={() => {
                  window._rlog(`_manager_to_attend`);
                  openLink(item.url);
                }}
              >
                <img src={item.img} />
                <div className="hr-li-desc">{item.title}</div>
              </span>
            ))}
          </div>
        </div>

        <WhiteSpace size="lg" />
        {
          this.adminContact()
        }
        {
          mainAdmin ? <div >
            <WhiteSpace size="lg" />
            {
              this.setHrRight()
            }
          </div> : ""
        }
        <div className="hr-m-leave"></div>
      </div>
    );
  }
}